package shiyan1;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Pipe {
    public static void main(String[] args) throws IOException, InterruptedException {
        PipedInputStream pipedInputStream=new PipedInputStream();
        PipedOutputStream pipedOutputStream=new PipedOutputStream();
        pipedInputStream.connect(pipedOutputStream);

        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                try {
                    pipedOutputStream.write("Hello,receiver! I`m sender".getBytes(StandardCharsets.UTF_8));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] b=new byte[1024];
                    List<Byte> bb=new ArrayList<>();
                    int read;
                    while((read=pipedInputStream.read(b))!=0)
                    {
                        byte[] newb=Arrays.copyOfRange(b,0,read);
                        System.out.println(new String(newb));
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }System.out.println("the following is from sender");
            }
        };
        Thread t1=new Thread(runnable1);
        Thread t2=new Thread(runnable2);
        t1.start();
        t2.start();
        t2.join();


    }
}
